#include <iostream>
#include <vector>
#include <stack>
using namespace std;


struct TreeNode {
    int val;
    TreeNode* left;
    TreeNode* right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode* left, TreeNode* right) : val(x), left(left), right(right) {}
};

class Solution {
public:
    TreeNode* _buildTree(vector<int>& preorder, vector<int>& inorder, int& begin, int mid, int end)
    {
        if (mid > end)
        {
            return nullptr;
        }
        int start = mid;
        while (start <= end)
        {
            if (inorder[start] == preorder[begin])
            {
                break;
            }
            start++;
        }
        TreeNode* node = new TreeNode(preorder[begin++]);
        node->left = _buildTree(preorder, inorder, begin, mid, start - 1);
        node->right = _buildTree(preorder, inorder, begin, start + 1, end);
        return node;
    }

    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
        int n = preorder.size();
        int begin = 0;
        return _buildTree(preorder, inorder, begin, 0, n - 1);
    }
};

//int main()
//{
//    vector<int> preorder = { 3,9,20,15,7 };
//    vector<int> inorder = { 9,3,15,20,7 };
//    Solution s;
//    s.buildTree(preorder, inorder);
//    return 0;
//}

class Solution {
public:
    vector<int> preorderTraversal(TreeNode* root) {
        stack<TreeNode*> st;
        vector<int> ret;
        TreeNode* cur = root;
        while (cur || !st.empty())
        {
            while (cur)
            {
                ret.push_back(cur->val);
                st.push(cur);
                cur = cur->left;
            }
            cur = st.top()->right;
            st.pop();
        }
        return ret;
    }
};

class Solution {
public:
    TreeNode* _buildTree(vector<int>& inorder, vector<int>& postorder, int& begin, int mid, int end)
    {
        if (mid < end)
        {
            return nullptr;
        }
        int rootie = mid;
        while (rootie >= end)
        {
            if (inorder[rootie] == postorder[begin])
            {
                break;
            }
            rootie--;
        }
        TreeNode* node = new TreeNode(postorder[begin--]);
        node->right = _buildTree(inorder, postorder, begin, mid, rootie + 1);
        node->left = _buildTree(inorder, postorder, begin, rootie - 1, end);
        return node;
    }
    TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
        int n = inorder.size() - 1;
        return _buildTree(inorder, postorder, n, n, 0);
    }
};